package com.tms.warehouse;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public abstract class BaseController extends HttpServlet {

	protected static final String ACTION_EDIT = "edit";
	protected static final String ACTION_DELETE = "delete";
	protected static final String ACTION_NEW = "new";
	protected static final String ACTION_SAVE = "save";

	protected static final String TARGET_SELF = "SELF";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String target = doListAction(req, resp);
		req.getRequestDispatcher(target).forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String target = null;
		if (req.getParameter(ACTION_NEW) != null) {
			target = doCreateAction(req, resp);
		} else if (req.getParameter(ACTION_EDIT) != null) {
			target = doEditAction(req, resp);
		} else if (req.getParameter(ACTION_DELETE) != null) {
			target = doDeleteAction(req, resp);
		} else if (req.getParameter(ACTION_SAVE) != null) {
			target = doSaveAction(req, resp);
		} else {
			target = doAdvancedAction(req, resp);
		}

		if (target != null) {
			if (!TARGET_SELF.equals(target)) {
				req.getRequestDispatcher(target).forward(req, resp);
			} else {
				doGet(req, resp);
			}
		}

	}

	protected String doAdvancedAction(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		throw new ServletException("No advanced action implemented");
	}

	protected abstract String doListAction(HttpServletRequest req,
			HttpServletResponse resp);

	protected abstract String doCreateAction(HttpServletRequest req,
			HttpServletResponse resp);

	protected abstract String doEditAction(HttpServletRequest req,
			HttpServletResponse resp);

	protected abstract String doDeleteAction(HttpServletRequest req,
			HttpServletResponse resp);

	protected abstract String doSaveAction(HttpServletRequest req,
			HttpServletResponse resp);

}
